<template>
  <div v-if="visible" class="floating-panel">
    <span class="close-btn" role="button" aria-label="关闭" tabindex="0" @click="handleCancel" @keydown.enter="handleCancel">×</span>
    <div class="floating-panel__header">提交</div>
    <div class="floating-panel__body">
      <!-- 操作按钮区域 -->
      <div class="actions">
        <el-button type="info" size="small" @click="noop" :disabled="loading">模型检查</el-button>
        <el-button type="info" size="small" @click="handleConfirm" :loading="saving">保存</el-button>
        <el-button type="info" size="small" @click="submitCalculation" :disabled="loading">提交计算</el-button>
        <el-button type="info" size="small" @click="noop" :disabled="loading">计算文件导出</el-button>
        <el-button type="info" size="small" @click="viewResults" :disabled="loading">查看结果</el-button>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { usePropertyForm } from '../composables/usePropertyForm'
import { ElMessage } from 'element-plus'
import { femCalculate } from '@/api/system/JavaFem'
import eventBus from "@/utils/eventBus";
import { useTreeStore } from '@/store/modules/tree' // 假设你的 pinia store 路径为 @/store/treeStore
// 声明可能由父组件传入的节点和项目ID（如果存在则保存时会真正持久化）
const props = defineProps<{ node?: any; projectId?: number | string | null; key?: string | number }>()
const emit = defineEmits<{ (e:'cancel'):void; (e:'confirm'):void }>()
const visible = ref(true)
function handleCancel(){ visible.value=false; emit('cancel') }
function handleKey(e:KeyboardEvent){ if(e.key==='Escape'&&visible.value){ handleCancel() } }
onMounted(()=>window.addEventListener('keydown',handleKey))
onBeforeUnmount(()=>window.removeEventListener('keydown',handleKey))
// 最小 form，只需一个字段即可满足 usePropertyForm 要求；若有真实字段可替换 temp
const form = reactive({ temp: '' })
const saving = ref(false)
const loading = ref(false) // 统一控制占位按钮的禁用状态
const treeStore = useTreeStore()
const { handleConfirm: _handleConfirm } = usePropertyForm(form, { node: props.node, projectId: props.projectId }, (e)=>emit(e as any))
async function handleConfirm(){
  saving.value = true
  try { await _handleConfirm() } finally { saving.value = false }
}
const viewResults = () => {
  console.log("viewResults clicked", props.node)
  // 检查 filePath 是否存在且非空
  const filePath = props.node?.property?.result?.filePath
  if (filePath) {
    // 通过 eventBus.emit 发送 filePath
    eventBus.emit('viewResultFilePath', filePath)
  } else {
    ElMessage.warning('未找到结果文件路径')
  }
}
// 提交计算：向 FEM 后端发送 POST 请求，参数为对象 { id: projectId }
const submitCalculation = async () => {
  if (!props.projectId) {
    ElMessage.warning('缺少 projectId，无法提交计算')
    return
  }

  // derive nodeKey: prefer props.key if provided, otherwise try props.node?.key
  const nodeKey = (props as any).key ?? props.node?.key
  if (!nodeKey) {
    ElMessage.warning('未提供节点 key（props.key 或 props.node.key），无法提交计算')
    return
  }

  loading.value = true
  try {
    const payload = {
      id: props.projectId,
      key: nodeKey
    }
    const res: any = await femCalculate(payload)
    ElMessage.success(res.msg)
    if (res.data ) {
      // 1. 更新当前节点 property
      props.node.property = res.data
      // 2. 同步 pinia 全局树
      // treeStore.updateNodeProperty(props.projectId, nodeKey, res.data)
    }
  } catch (err: any) {
    console.error('submitCalculation error', err)
    ElMessage.error(err?.message || '提交计算失败')
  } finally {
    loading.value = false
  }
}
// end
function noop() { /* 占位无操作 */ }
</script>
<style scoped lang="scss">
@use './common.scss' as *;
.actions { display:flex; flex-wrap:wrap; gap:8px; margin-top:8px; }
</style>